package org.snail.transport.impl;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;

import java.util.concurrent.TimeUnit;

/**
 * 重连失败的时候触发
 * Created by fish on 17/8/26.
 */
public class ConnectionListener implements ChannelFutureListener {

    private NettyConnector nettyConnector;

    private HashedWheelTimer timer;

    public ConnectionListener(NettyConnector nettyConnector,HashedWheelTimer timer) {
        this.nettyConnector = nettyConnector;
        this.timer = timer;
    }
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (!channelFuture.isSuccess()) {
            timer.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    nettyConnector.connect(nettyConnector.getHost(), nettyConnector.getPort());
                }
            },2L, TimeUnit.SECONDS);
        }
    }
}